import * as stringify from 'qs/lib/stringify';
import * as parse from 'qs/lib/parse';

export default {
    mounted() {
        if (this.form instanceof Object) {
            // eslint-disable-next-line no-restricted-globals
            const query = parse(location.search.replace('?', ''));
            const params = this.form;
            for (const key in params) {
                if (!Object.prototype.hasOwnProperty.call(params, key)) continue;
                if (typeof query[key] === 'undefined') continue;
                if (key.includes('page')) {
                    params[key] = +query[key];
                    continue;
                }
                if (key.includes('_id') && typeof query[key] === 'string') {
                    params[key] = +query[key];
                    continue;
                }
                if (Array.isArray(params[key]) && !Array.isArray(query[key])) {
                    params[key] = new Array(query[key]);
                    continue;
                }
                if (query[key] === 'true') {
                    params[key] = true;
                    continue;
                }
                if (query[key] === 'false') {
                    params[key] = false;
                    continue;
                }
                if (typeof query[key] === 'string' && query[key] && !Number.isNaN(+query[key])) {
                    params[key] = +query[key];
                    continue;
                }

                params[key] = query[key];
            }
            for (const key in query) {
                if (!Object.prototype.hasOwnProperty.call(query, key)) continue;
                if (typeof params[key] !== 'undefined') continue;
                params[key] = query[key];
            }
            params.size = +params.size;
            this.form = params;
        }
    },
    watch: {
        loading(val) {
            if (this.form instanceof Object) {
                // eslint-disable-next-line no-restricted-globals
                if (!val) history.replaceState(null, null, `?${stringify(this.form, { arrayFormat: 'repeat' })}`);
            }
        },
    },
};
